package com.sa.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Architecture Station
 * @version 1.0
 */
//@Component
//@Order(1)
@Slf4j
public class AuthenticationGlobalFilter implements GlobalFilter {

    // 认证头
    private static final String AUTHENTICATION_HEADER = "Authorization";

    // 登录URL
    private static final String LOGIN_URL = "/user/api/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("URL:{}", exchange.getRequest().getPath());

        // 如果请求路径包含登录URL，则直接放行
        if (exchange.getRequest().getPath().toString().contains(LOGIN_URL)) {
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst(AUTHENTICATION_HEADER);
        if (token == null || !isValid(token)) {
            // 返回401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 该请求结束
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }

    private boolean isValid(String token) {
        // 通过Token工具类校验合法性、有效期
        return true;
    }
}
















